<?php
//app订单处理
namespace App\Http\Controllers\App;
use App\Http\Controllers\App\BaseController as Controller;
use App\Tools\WechatSend;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use App\Models\Order;
use App\Models\Shop;
use App\Models\ShopDish;
use App\Tools\MoneyChange;
use App\Models\ShopDishAttribute;
class OrderOperation extends Controller
{

    protected $thisLoginClerk;
    public function __construct(Request $request)
    {
        $checkThisClerk = $this->getShopUserID($request->token,$request->device_id);
        if(!$checkThisClerk){
            return show(2001,'无效token');
        }else{//判断用户角色
            //权限处理
            switch($checkThisClerk->role){
                case -1:    // 商家和经理有权限处理
                case 2:
                    $this->thisLoginClerk = $checkThisClerk;
                    break;
                case 0:
                case 1:
                case 3:
                    return show(2002,'没有权限');
                    break;
                default:
                    return show(2002,'没有权限');
                    break;
            }
        }
    }

    //外卖接单
    public function sureOrder(Request $request){
        $rules = [
            'order_id' => 'required|integer|exists:orders,id',
        ];
        $message = [
            'order_id.*'=>'订单不存在'
        ];
        //验证参数
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(2003,$validator->errors()->first());
        }
        //验证订单
        $order = Order::where('order_type',0)->where('order_status',2)->find($request->order_id);
        if(!$order){
            return show(2003,'订单验证错误，无法接单');
        }
        //订单归属
        if(!$this->orderbelong($order->shop_id)){
            return show(2002,'没有权限');
        }
        $order->order_status = 3;
        // @todo 接达达配送api
        $order->save();
        return show(200,'确定接单成功');
    }

    //外卖拒单
    public function rejectOrder(Request $request){
        try{
            $rules = [
                'order_id' => 'required|integer|exists:orders,id',
            ];
            $message = [
                'order_id.*'=>'订单不存在'
            ];
            //验证参数
            $validator = Validator::make($request->all(), $rules,$message);
            if ($validator->fails()) {
                return show(2003,$validator->errors()->first());
            }
            //验证订单
            $order = Order::where('order_type',0)->where('order_status',2)->find($request->order_id);
            if(!$order){
                return show(2003,'订单验证错误，无法拒单');
            }
            //订单归属
            if(!$this->orderbelong($order->shop_id)){
                return show(2002,'没有权限');
            }
            $order->order_status = -3;
            $order->save();
            //加钱加流水
            $money = new MoneyChange();
            $money->add_money($order->user_id,$order->order_amount,1,'（商家拒单）订单编号：'.$order->order_number,0,'退款');
            return show(200,'拒单成功');
        }catch (\Exception $e){
            return show(201,'拒单失败');
        }
    }
    //预定到店
    public function arriveShop(Request $request){
        try{
            $rules = [
                'order_id' => 'required|integer|exists:orders,id',
            ];
            $message = [
                'order_id.*'=>'订单不存在'
            ];
            //验证参数
            $validator = Validator::make($request->all(), $rules,$message);
            if ($validator->fails()) {
                return show(2003,$validator->errors()->first());
            }
            //验证订单
            $order = Order::where('order_type',1)->where('order_status',2)->find($request->order_id);
            if(!$order){
                return show(201,'订单验证错误，无法选择到店');
            }
            //订单归属
            if(!$this->orderbelong($order->shop_id)){
                return show(201,'没有权限');
            }
            $order->order_status = 3;
            $order->save();
            return show(200,'选择到店成功');
        }catch (\Exception $e){
            return show(201,'选择到店失败');
        }

    }
    //预定加菜
    public function reserveAddDishes(Request $request){
        try{
            $rules = [
                'cart' => 'required|array',
            ];
            $message = [
                'cart.*'=>'购物车不存在'
            ];
            //验证参数
            $validator = Validator::make($request->all(), $rules,$message);
            if ($validator->fails()) {
                return show(2003,$validator->errors()->first());
            }
            //验证订单
            $order = Order::where('order_type',1)->where('order_status',3)->find($request->cart['order_id']);
            if(!$order){
                return show(2003,'订单验证错误，无法加菜');
            }
            //订单归属
            if(!$this->orderbelong($order->shop_id)){
                return show(2002,'没有权限');
            }
            //价格验证
            $top_amount=$top_price = 0;
            foreach($request->cart['dish'] as $k=>$v)
            {
                $dishes = ShopDish::find($v['dishes_id'])->toArray();
                if($dishes['is_attr']==1){
                    //获取数据库的规格计算
                    $ShopDishAttribute = ShopDishAttribute::where('dish_id',$dishes['id'])->get();
                    $spec_price = 0;
                    foreach($ShopDishAttribute as $k2=>$v2)
                    {
                        foreach(explode(',',$v2['spec']) as $k3=>$v3)
                        {
                            $spec = explode('|',$v3);
                            //获取购物车的规格计算
                            $cart_dish_spec = explode(',',$request->cart['dish'][$k]['spec']);
                            foreach($cart_dish_spec as $k4=>$v4){
                                $cart_spec = explode('|',$v4);
                                if($cart_spec[0]==$spec[0]){
                                    $spec_price += floatval($spec[1]);
                                }
                            }
                        }
                    }
                    //（规格价+基础价）* 数量 * 折扣
                    $top_amount += ($spec_price+$dishes['price'])*$request->cart['dish'][$k]['goods_number']*$dishes['discount'];
                    $top_price  += ($spec_price+$dishes['price'])*$request->cart['dish'][$k]['goods_number'];
                }else{
                    $top_amount += $dishes['price'] * $request->cart['dish'][$k]['goods_number']*$dishes['discount'];
                    $top_price  += $dishes['price'] * $request->cart['dish'][$k]['goods_number'];
                }
            }
            //强转防止溢出
            $top_amount = round($top_amount,2);
            //更新订单
            $order->order_price = $order->order_price+$top_amount;
            $order->save();
            $dishesdata = [];
            //添加菜式到订单
            foreach($request->cart['dish'] as $k=>$v){
                $dishesdata[$k]['dishes_id']=$v['dishes_id'];
                $dishesdata[$k]['dishes_name']=$v['dishes_name'];
                $dishesdata[$k]['goods_number']=$v['goods_number'];
                $dishesdata[$k]['price']=$v['price'];
                $dishesdata[$k]['sell_price']=$v['sell_price'];
                $dishesdata[$k]['is_attr']=$v['is_attr'];
                $dishesdata[$k]['spec']=$v['spec'];
                $dishesdata[$k]['amount']  = $v['goods_number']*$v['sell_price'];
                $dishesdata[$k]['order_id']=$request->cart['order_id'];
            }
            DB::table('order_details')->insert($dishesdata);
            return show(200,'加菜成功');
        }catch (\Exception $e){
            //dd($e->getMessage());
            return show(201,'加菜失败');
        }
    }

    //预定修改价格
    public function reserveEditMenu(Request $request){
        try{
            $rules = [
                'order_id' => 'required|integer|exists:orders,id',
                'price'    => 'required|numeric'
            ];
            $message = [
                'order_id.*'=>'订单不存在',
                'price.*'=>'价格有误'
            ];
            //验证参数
            $validator = Validator::make($request->all(), $rules,$message);
            if ($validator->fails()) {
                return show(2003,$validator->errors()->first());
            }
            //验证订单
            $order = Order::where('order_type',1)->where('order_status',3)->find($request->order_id);
            if(!$order){
                return show(2003,'订单验证错误');
            }
            //订单归属
            if(!$this->orderbelong($order->shop_id)){
                return show(2002,'没有权限');
            }
            $price = number_format($request->price,2);
            if($price < $order->amount){
                return show(2003,'订单金额小于已支付定金');
            }
            $order->order_price = $price;
            $order->save();
            return show(200,'修改价格成功',[
                'price'=>$price
            ]);
        }catch (\Exception $e){
            return show(201,'修改价格失败');
        }

    }

    //同意退款
    public function  sureForRefund(Request $request){
        try{
            $rules = [
                'order_id' => 'required|integer|exists:orders,id',
            ];
            $message = [
                'order_id.*'=>'订单不存在'
            ];
            //验证参数
            $validator = Validator::make($request->all(), $rules,$message);
            if ($validator->fails()) {
                return show(2003,$validator->errors()->first());
            }
            //验证订单
            $order = Order::whereIn('order_type',1)->where('order_status',-1)->find($request->order_id);
            if(!$order){
                return show(2003,'订单验证错误，无法选择到店');
            }
            //订单归属
            if(!$this->orderbelong($order->shop_id)){
                return show(2002,'没有权限');
            }
            $order->order_status =-2;
            $order->save();
            //加钱加流水
            $money = new MoneyChange();
            if($order->order_type==0){//外卖
                $money->add_money($order->user_id,$order->order_amount,1,'（商家拒单）订单编号：'.$order->order_number,0,'退款');
            }else{//预订
                //退款扣除用户退款百分比
                //...................
                $money->add_money($order->user_id,$order->order_amount,1,'（商家拒单）订单编号：'.$order->order_number,0,'退款');
            }
            return show(200,'同意退款成功');
        }catch (\Exception $e){
            return show(201,'同意退款失败');
        }
    }
    
    //订单归属
    protected  function  orderbelong($shopid){

        if ($this->thisLoginClerk->role == '-1'){// 商家
            // 判断这个商铺是否属于该商家
            $user_id = $this->thisLoginClerk->id;
            if (!Shop::checkIsShop($shopid,$user_id)){
                return false ;
            }
            return true;
        }else{// 服务员
            // 判断这个商铺是否属于当前服务员的商铺
            if( $shopid != $this->thisLoginClerk->shop_id){
                return false;
            }
            return true;
        }

    }

}
